/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package me.panpf.sketch.sample.bean;

import me.panpf.sketch.sample.AppConfig;
import me.panpf.sketch.sample.item.SettingsItemProvider;
import me.panpf.sketch.util.Log;
import ohos.agp.components.BaseItemProvider;
import ohos.app.Context;

/**
 * CheckMenu
 */
public class CheckMenu extends CommonItem {
    private Context mContext;

    /**
     * title
     */
    public String title;
    private AppConfig.Key key;
    private OnCheckedChangedListener onCheckedChangedListener;

    public CheckMenu(Context context, String title, AppConfig.Key key, OnCheckedChangedListener onCheckedChangedListener) {
        super(TYPE_CHECK_MENU);
        this.mContext = context;
        this.title = title;
        this.key = key;
        this.onCheckedChangedListener = onCheckedChangedListener;
    }

    private boolean isChecked;

    public boolean isChecked() {
        isChecked = AppConfig.getBoolean(mContext, key);

        return isChecked;
    }

    /**
     * onClick
     * @param provider
     */
    public void onClick(BaseItemProvider provider) {
        boolean newChecked = !isChecked;

        if (onCheckedChangedListener != null) {
            onCheckedChangedListener.onCheckedChangedBefore(newChecked);
        }

        AppConfig.putBoolean(mContext, key, newChecked);

        if ((provider instanceof SettingsItemProvider)) {
            SettingsItemProvider settingsItemProvider = (SettingsItemProvider) provider;
            int changedPos = settingsItemProvider.getList().indexOf(this);
            settingsItemProvider.notifyDataSetItemChanged(changedPos);
        }

        if (onCheckedChangedListener != null) {
            onCheckedChangedListener.onCheckedChanged(newChecked);
        }
    }

    interface OnCheckedChangedListener {
        void onCheckedChangedBefore(boolean checked);

        void onCheckedChanged(boolean checked);
    }
}
